package juc;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author G_Y
 * @Date 2021/5/14 11:59
 * @Description: // TODO
 **/
public class LockTest1 {
    public static void main(String[] args) {
        UserObj user1 = new UserObj();
        UserObj user2 = new UserObj();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                user1.f1();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                user2.f1();
            }
        });
        thread1.start();
        thread2.start();
        System.out.println("main over");
    }
}


class UserObj {
    private static Lock lock = new ReentrantLock();

    public void f1() {
            lock.lock();
        boolean b = false;
        try {
            b = lock.tryLock(4L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!b) {
            // 没有拿到
            // 自己选择实现方式
            return;
        }
        if (b) {
            try {
                for (int i = 1; i <= 10; i++) {
                    System.out.println(i);
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }

    }
}


